// API接口管理
import { BASE_URL } from './config.js'

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 添加通用请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    }
    
    // 添加token（如果有）
    const token = uni.getStorageSync('token')
    if (token) {
      header.Authorization = `Bearer ${token}`
    }
    
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: header,
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            // 业务错误
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          // Token无效或过期，尝试刷新token
          handleTokenExpired(options, resolve, reject)
        } else {
          // 其他HTTP错误
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 处理token过期
const handleTokenExpired = async (originalOptions, resolve, reject) => {
  try {
    const refreshToken = uni.getStorageSync('refreshToken')
    if (!refreshToken) {
      // 没有refreshToken，清除登录信息
      clearLoginData()
      reject({ code: 401, message: 'Token已过期，请重新登录' })
      return
    }
    
    // 尝试刷新token
    const refreshResponse = await refreshUserToken(refreshToken)
    if (refreshResponse.code === 0) {
      // 刷新成功，重新发起原请求
      const newToken = refreshResponse.data.token
      originalOptions.header = {
        ...originalOptions.header,
        Authorization: `Bearer ${newToken}`
      }
      
      // 重新发起请求
      const retryRequest = request(originalOptions)
      retryRequest.then(resolve).catch(reject)
    } else {
      // 刷新失败，清除登录信息
      clearLoginData()
      reject({ code: 401, message: 'Token刷新失败，请重新登录' })
    }
  } catch (error) {
    // 刷新token失败
    clearLoginData()
    reject({ code: 401, message: 'Token刷新失败，请重新登录' })
  }
}

// 刷新token
const refreshUserToken = (refreshToken) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + '/auth/simple-wechat/refresh?refreshToken=' + refreshToken,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          // 更新本地token
          uni.setStorageSync('token', res.data.data.token)
          if (res.data.data.refreshToken) {
            uni.setStorageSync('refreshToken', res.data.data.refreshToken)
          }
          resolve(res.data)
        } else {
          reject(res.data || { code: -1, message: '刷新token失败' })
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 清除登录数据
const clearLoginData = () => {
  uni.removeStorageSync('token')
  uni.removeStorageSync('refreshToken')
  uni.removeStorageSync('userInfo')
  uni.removeStorageSync('wechatUserInfo')
  uni.removeStorageSync('openid')
  uni.removeStorageSync('sessionKey')
  uni.removeStorageSync('tokenType')
  uni.removeStorageSync('expiresIn')
  uni.removeStorageSync('loginStatus')
}

// API接口定义
const api = {
  // 用户相关
  user: {
    // 获取用户信息
    getUserInfo() {
      return request({
        url: '/user/info',
        method: 'GET'
      })
    },
    
    // 更新用户信息
    updateUserInfo(data) {
      return request({
        url: '/user/update',
        method: 'POST',
        data
      })
    }
  },
  
  // 微信登录相关接口
  wechat: {
    // 微信登录 - 通过code获取用户信息
    login(code) {
      return request({
        url: '/petbone/wx/miniapp/login',
        method: 'POST',
        data: {
			code,
		}
      })
    },
    
    // 获取微信用户信息（需要用户授权）
    getUserProfile(encryptedData, iv) {
      return request({
        url: '/auth/simple-wechat/userinfo',
        method: 'POST',
        data: {
          encryptedData,
          iv
        }
      })
    },
    
    // 获取微信用户手机号（需要用户授权）
    getPhoneNumber(encryptedData, iv) {
      return request({
        url: '/auth/simple-wechat/phone-number',
        method: 'POST',
        data: {
          encryptedData,
          iv
        }
      })
    },
    
    // 刷新用户token（已移至内部实现，不再对外暴露）
    // refreshToken方法已整合到request拦截器中自动处理
  },
  
  // 订单相关
  order: {
    // 验证订单号
    verifyOrder(orderNumber) {
      return request({
        url: '/order/verify',
        method: 'POST',
        data: { orderNumber }
      })
    },
    
    // 获取订单历史
    getOrderHistory(page = 1, limit = 10) {
      return request({
        url: '/order/history',
        method: 'GET',
        data: { page, limit }
      })
    }
  },
  
  // 抽奖相关
  lottery: {
    // 获取抽奖配置
    getLotteryConfig() {
      return request({
        url: '/lottery/config',
        method: 'GET'
      })
    },
    
    // 获取用户抽奖次数
    getLotteryCount() {
      return request({
        url: '/lottery/count',
        method: 'GET'
      })
    },
    
    // 执行抽奖
    drawLottery() {
      return request({
        url: '/lottery/draw',
        method: 'POST'
      })
    },
    
    // 获取抽奖记录
    getLotteryRecords(page = 1, limit = 10) {
      return request({
        url: '/lottery/records',
        method: 'GET',
        data: { page, limit }
      })
    }
  },
  
  // 兑换相关
  exchange: {
    // 获取兑换配置
    getExchangeConfig() {
      return request({
        url: '/exchange/config'
      })
    },
    
    // 提交兑换申请
    submitExchange(data) {
      return request({
        url: '/exchange/submit',
        method: 'POST',
        data
      })
    },
    
    // 获取兑换记录
    getExchangeRecords(page = 1, limit = 10) {
      return request({
        url: '/exchange/records',
        data: { page, limit }
      })
    }
  },
  
  // 商品相关API
  product: {
    // 获取商品列表
    getProductList(params = {}) {
      return request({
        url: '/petbone/miniapp/product/page',
        data: params
      })
    },
    
    // 获取商品详情
    getProductDetail(productId) {
      return request({
        url: `/petbone/miniapp/product/details/${productId}`
      })
    },
    
    // 搜索商品
    searchProducts(keyword) {
      return request({
        url: '/products/search',
        data: { keyword }
      })
    }
  },
  
  // 地址相关API
  address: {
    // 获取地址列表
    getAddressList(openId) {
      return request({
        url: `/petbone/miniapp/userAddress/list/${openId}`,
      })
    },
    
    // 获取地址详情
    getAddressDetail(addressId) {
      return request({
        url: `/petbone/miniapp/userAddress/details/${addressId}`
      })
    },
    
    // 新增地址
    createAddress(addressData) {
      return request({
        url: '/petbone/miniapp/userAddress',
        method: 'POST',
        data: addressData
      })
    },
    
    // 更新地址
    updateAddress(addressId, addressData) {
      return request({
        url: `/petbone/miniapp/userAddress/${addressId}`,
        method: 'PUT',
        data: addressData
      })
    },
    
    // 删除地址
    deleteAddress(addressId) {
      return request({
        url: `/petbone/miniapp/userAddress/${addressId}`,
        method: 'DELETE'
      })
    },
    
    // 设置默认地址
    setDefaultAddress(addressId) {
      return request({
        url: `/petbone/miniapp/userAddress/setDefault/${addressId}`,
        method: 'GET',
      })
    },
    
    // 获取默认地址
    getDefaultAddress(openId) {
      return request({
        url: `/petbone/miniapp/userAddress/default/${openId}`
      })
    }
  },
  
  // 订单相关API
  shopping: {
    // 获取订单列表
    getOrderList(params = {}) {
      return request({
        url: '/orders',
        data: params
      })
    },
    
    // 获取订单详情
    getOrderDetail(orderId) {
      return request({
        url: `/orders/${orderId}`
      })
    },
    
    // 创建订单
    createOrder(orderData) {
      return request({
        url: '/orders',
        method: 'POST',
        data: orderData
      })
    },
    
    // 取消订单
    cancelOrder(orderId) {
      return request({
        url: `/orders/${orderId}/cancel`,
        method: 'PUT'
      })
    },
    
    // 确认收货
    confirmReceived(orderId) {
      return request({
        url: `/orders/${orderId}/confirm`,
        method: 'PUT'
      })
    },
    
    // 更新订单状态
    updateOrderStatus(orderId, status) {
      return request({
        url: `/orders/${orderId}/status`,
        method: 'PUT',
        data: { status }
      })
    }
  },
  
  // 支付相关API
  payment: {
    // 创建微信支付订单
    createWechatPayment(paymentData) {
      return request({
        url: '/payments/wechat/create',
        method: 'POST',
        data: paymentData
      })
    },
    
    // 查询支付状态
    getPaymentStatus(paymentId) {
      return request({
        url: `/payments/${paymentId}/status`
      })
    },
    
    // 支付回调处理
    handlePaymentCallback(callbackData) {
      return request({
        url: '/payments/callback',
        method: 'POST',
        data: callbackData
      })
    }
  }
}

// 导出API
export default api

// 也可以单独导出request方法供其他地方使用
export { request }